<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
 use SimpleSoftwareIO\QrCode\Facades\QrCode;

/**
 * App\PrizeSetting
 *
 * @property int $id
 * @property string|null $name
 * @property float|null $chance
 * @property \Carbon\Carbon|null $created_at
 * @property \Carbon\Carbon|null $updated_at
 * @property string|null $image 图片
 * @method static \Illuminate\Database\Eloquent\Builder|\App\PrizeSetting whereChance($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\PrizeSetting whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\PrizeSetting whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\PrizeSetting whereImage($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\PrizeSetting whereName($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\PrizeSetting whereUpdatedAt($value)
 * @mixin \Eloquent
 */
class PrizeSetting extends Model
{
    protected  $table='prize_setting';
    //计算 处理中奖
    public function handlePrize($member_id,PayOrder $order){
        $data=$this->handle();
        if(!empty($data)){
            $this->writingToRecode($member_id,$order->id,$data);
            return true;
        }else{
            return false;
        }
    }

    //计算中奖结果
    protected function handle(){
        $prizes=self::all()->toArray();
        $data=[];
        foreach ($prizes as $k=>$v){
            $num=(int)floatval($v['chance']);

            for($i=0;$i<$num;$i++){
                array_push($data,$v);
            }
        }
        $num= count($data);
        if($num>=100) {
            $empty_num =0;
        }else{
            $empty_num=100-$num;
        }
        for ($i=0;$i<$empty_num;$i++){
            array_push($data,[]);
        }
        //计算结果
        return $data[array_rand($data)];
    }
    protected function writingToRecode($member_id,$order_id,$data){
        $memerPrize=new MemberPrize();
        $memerPrize->order_id=$order_id;
        $memerPrize->member_id=$member_id;
        $memerPrize->prize_id=$data['id'];
        $memerPrize->prize_name=$data['name'];
        $memerPrize->image=$data['image'];
        $memerPrize->save();
        $memerPrize->qrcode=$this->prizeQrcode($memerPrize);
        $memerPrize->save();
    }
    public function prizeQrcode(MemberPrize $memberPrize){
            $member_id= $memberPrize->member_id;
            $id=$memberPrize->id;
            $sign= encrypt(serialize(['member_id'=>$member_id,'memberPrize_id'=>$id]));
            $filepath='public/prizeCode/'.$memberPrize->id.'.png';
            if(!file_exists(storage_path('/app/'.$filepath))) {
                $asset = \Storage::put($filepath, QrCode::format('png')->size(300)->generate(route('memberPrize',                   ['sign' => $sign])));
            }
          return '/prizeCode/'.$memberPrize->id.'.png';
    }




}
